import { InboxOutlined } from "@ant-design/icons";
import {Form, Input, message, Modal, Select, Upload} from "antd";
import React, {useEffect, useState} from "react";
import {FormPost, HttpGet} from "../../utils/http";

type ResourceProps = {
    visible: boolean;
    type: "image" | "document" | "video" | "other";
    cate_id: number;
    multiple?: boolean;
    max?: number;
    onCancel: (refresh: boolean) => void;
}



interface FromProp {
    cate_id: number;
    tags: string[];
    brief: string;
    file: any
}


const title = (type: string):string => {
    switch (type) {
        case "image":
            return "上传图片";
        case "document":
            return "上传文档";
        case "video":
            return "上传视频";
        case "other":
            return "其他资源";
        default:
            return "上传资源"
    }
}

const layout = {
    labelCol: { span: 2 },
    wrapperCol: { span: 22 },
};

export const ResourceUpload:React.FC<ResourceProps> = ({
    visible,
    onCancel,
    type,
    max = 5,
    multiple= false,
    cate_id
}) => {

    const [form] = Form.useForm<FromProp>();

    const [tagList, setTagList] = useState<string[]>([])


    useEffect(() => {
        if (visible) {
            loadTags()
        } else {
            setTagList([])
        }
    }, [visible])


    const loadTags = () => {
        HttpGet<string[]>('/api/resources/tags').then(res => {
            if (res.code === '100200') {
                setTagList(res.data)
            }
        })
    }


    const beforeUpload = (file: any) => {

        if (file.type.indexOf("image/") === -1) {
            message.warn('请上传图片');
            return false;
        }
        return false;
    }

    const uploadResource = () => {
        form.validateFields().then(values => {
            console.log(values);
            const formData = new FormData();
            formData.append("file", values.file.file)
            formData.append("tags", values.tags.join(","))
            formData.append("cate_id", "" + values.cate_id)
            formData.append("brief", values.brief)
            FormPost<any>('/api/resources/upload', formData).then(res => {
                if (res.code === '100200') {
                    form.resetFields();
                    values.file.fileList = []
                    values.file.file = {}
                    onCancel(true)
                }
            })

        }).catch(info => {
            console.log('Validate Failed:', info);
        });
    }


    return <Modal
        maskClosable={false}
        visible={visible}
        title={title(type)}
        okText="保存"
        cancelText="取消"
        onCancel={() => onCancel(false)}
        onOk={uploadResource}
    >
        <Form
            {...layout}
            form={form}
            layout="horizontal"
            name="form_in_modal"
        >
            <Form.Item name="cate_id" style={{display: 'none'}} initialValue={cate_id}>
                <Input value={cate_id} />
            </Form.Item>
            <Form.Item name="file" label="资源">
                <Upload.Dragger
                    multiple={false}
                    listType="picture"
                    beforeUpload={(file: any) => beforeUpload(file)}
                >
                    <p className="ant-upload-drag-icon">
                        <InboxOutlined />
                    </p>
                    <p className="ant-upload-text">单击或拖动文件到此区域进行上传</p>
                </Upload.Dragger>
            </Form.Item>
            <Form.Item name="tags" label="标签">
                <Select mode="tags" style={{ width: '100%' }} placeholder="请输入资源标签">
                    {tagList.length > 0 &&
                    tagList.map(
                        (item, index) =>
                            <Select.Option
                                value={item}
                                key={index}
                            >
                                {item}
                            </Select.Option>
                    )}
                </Select>
            </Form.Item>
            <Form.Item name="brief" label="备注">
                <Input.TextArea rows={3} placeholder="请输入资源备注" />
            </Form.Item>
        </Form>
    </Modal>

}
